package org.hot100_3;

public class leetcode53 {

    public int maxSubArray2(int[] nums) {
        int n = nums.length;
        int[] dp = new int[n];

        dp[0] = nums[0];

        int max =dp[0];

        for (int i = 1; i < n; i++) {
            if (dp[i - 1] > 0) {
                dp[i] = dp[i - 1] + nums[i];
            } else {
                dp[i] = nums[i];
            }
         max =Math.max(dp[i], max);
        }
        return max;
    }


    //回溯解法 超时
    int maxSum = Integer.MIN_VALUE;

    public int maxSubArray(int[] nums) {

        for (int i = 0; i < nums.length; i++) {
            backtracking(nums, i, 0);
        }

        return maxSum;
    }

    private void backtracking(int[] nums, int index, int sum) {
        if (index == nums.length) {
            return;
        }

        sum += nums[index];
        maxSum = Math.max(sum, maxSum);
        backtracking(nums, index + 1, sum);
    }
}
